/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.utils;

import java.io.IOException;
import java.util.ArrayList;

import com.hiddenequity.servicedaccountservice.ServicedAccountService;
import com.hiddenequity.servicedaccountservice.ServicedAccountServiceParser;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

public class AuthService{
	
	public static String authToken;
	
	private static int accountNumber;
    
	public static String accountEmail;
	
	public static final String devToken = ""; // <- Developer token Here

	public static String CustomerId = null;
	
	private static Account[] accounts;
	
	private static AccountManager accountManager;
	
	public static ArrayList<String> accountNames = new ArrayList<String>();
	
	public static String clientId = null;
	
	/*
	 * Constructor
	 */
    public AuthService(Activity activity, Application application) {
    	if(authToken == null){
        	
    		getAccountList(activity);
        	getAccountNames();

        	accountNumber = AppPreferences.LoadPreferenceInt("accountNumber", -1,  application);
        	
        	if(accountNumber != -1 && accounts.length >= accountNumber){
        		performLogin(accountNumber, application, activity);

        	}
    	}
    	
    	if(clientId == null){
    		if(authToken != null){
				
				String response = Communication.postSOAP(
						ServicedAccountService.URL_SERVICED_ACCOUNT_SERVICE ,
						ServicedAccountService.getServicedAccountGraph());
	
				ServicedAccountServiceParser parser = new ServicedAccountServiceParser(response);
				clientId = parser.getCustomerId();
				//responseErrorString = parser.checkForErrors();
    		}
    	}
	}//Constructor
    
    
    
    /*
     * Get google linked accounts
     */
    public static void getAccountList(Activity activity){
    	accountManager = AccountManager.get(activity.getBaseContext()); 
    	accounts = accountManager.getAccountsByType("com.google");
    }//getAccountList

    
    
    /*
     * Get accounts names
     */
    private void getAccountNames(){
    	accountNames.clear();
    	String accName = null;
    	for (Account account : accounts) {
    		accName = account.name;
    		accountNames.add(accName);
    	}
    }//getAccountName
    
    
    
	/*
	 * Perform login process
     * Get AuthToken from android linked account
     */
    public static void performLogin(int accountNumber, Application application, Activity activity) {
    	AppPreferences.SavePreferenceInt("accountNumber", accountNumber, application);
    	
    	Account acct = accounts[accountNumber];
    	
    	accountEmail = acct.name;

    	AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(acct, "adwords", null, activity, null, null);

    	Bundle authTokenBundle = null;
		
    	try {
			authTokenBundle = accountManagerFuture.getResult();
		} catch (OperationCanceledException e) {
			e.printStackTrace();
		} catch (AuthenticatorException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
    	if(authToken != null) 
    		performLogout(application);
   		authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();  	
    }//getAuthToken	
	
    
    
    /*
     * Perform Logout
     * Release AuthToken
     */
    public static void performLogout(Application application){
    	releaseAuthToken();
    	AppPreferences.RemovePreference("accountNumber", application);
    	
    	authToken = null;   	
    	accountNumber = -1;
    	accountEmail = null;
    	CustomerId = null;
    }//releaseAthToken
    
    
    
    /*
     * Invalidate developer token
     */
    public static void releaseAuthToken(){
    	if(authToken == null)
    		return;
    	accountManager.invalidateAuthToken("com.google", authToken);
    	authToken = null;
    }
    
}
